package main

import (
	"fmt"
	"learndemo/gosync"
	"net/http"
	"sync"
	"time"
)

func main()  {
	muTest()
	muTest2()
	//wgTest()
	//println("over")

	//go task(2)
	//go task(3)
	//
	//time.Sleep(time.Second * 8)
}

func task(id int)  {
	for i:=0;i<6;i++ {
		fmt.Printf("%d:%d\n",id,i)
		time.Sleep(time.Second)
	}
}

//wait group
func wgTest()  {
	var wg sync.WaitGroup
	var urls = []string{
		"https://www.github.com/",
		"http://www.baidu.com/",
		"https://goatup.cn/api/v1/server/activity/coupon-activity/get-data?coupon_id=260",
	}

	for _,url := range urls  {
		wg.Add(1)

		go func(url string) {
			defer wg.Done()

			_,error := http.Get(url)
			fmt.Println(url,error)
		}(url)
	}

wg.Wait()
}

//计数器 mutex锁
func muTest()  {
	var wg sync.WaitGroup
	var mu sync.Mutex
	num := 0

	for i := 1; i <= 100;i++  {
		wg.Add(1)

		go func() {
			defer wg.Done()
			for j := 1;j <= 1000 ; j++ {
				mu.Lock()
				num++
				mu.Unlock()
			}
		}()
	}

	wg.Wait()
	fmt.Printf("count_num:%d",num)
}

func muTest2()  {
	var counter gosync.Counter
	var wg sync.WaitGroup
	for i := 1; i<= 100; i++  {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j:= 1; j<= 1000; j++ {
				counter.Incr()
			}
		}()
	}
	wg.Wait()

	fmt.Printf("count_num2:%d",counter.Count())
}
